<template>
  <div class="product-detail">
    <van-nav-bar title="商品列表" left-arrow @click-left="goBack">
      <template #right>
        <van-icon name="share-o" size="20" @click="showShareModal = true" class="share-icon" />
      </template>
    </van-nav-bar>

    <!-- 商品图片 -->
    <div class="img-container">
      <img :src="product.image_url" :alt="product.name" class="product-img" v-if="product.image_url" />
    </div>

    <!-- 商品基本信息 -->
    <div class="info-container">
      <!-- 商品名称 -->
      <h1 class="product-name">{{ product.name || '商品名称' }}</h1>

      <!-- 价格区域 -->
      <div class="price-box">
        <span class="current-price">¥{{ totalPrice.toFixed(1) }}</span>
        <!-- <span class="current-price">¥{{ product.price ? product.price.toFixed(2) : '0.00' }}</span> -->
        <span class="original-price" v-if="product.original_price">原价:¥{{ product.original_price.toFixed(2) }}</span>
      </div>

      <!-- 库存和销量 -->
      <div class="stock-sales">
        <span>库存:{{ product.inventory || '0' }}</span>
        <span>销量:{{ product.sales || '0' }}</span>
      </div>

      <!-- 规格选择区 -->
      <div class="spec-container">
        <div class="spec-title">规格选择:</div>
        <div class="spec-group" v-for="(group, groupIndex) in specGroups" :key="groupIndex">
          <div class="spec-name">{{ group.name }}:</div>
          <div class="spec-options">
            <button v-for="(option, optIndex) in group.options" :key="optIndex" class="spec-option"
              :class="{ active: group.selectedOption === option.name }" @click="selectSpec(groupIndex, option.name)">
              {{ option.name }}
            </button>
          </div>
        </div>
      </div>

      <!-- 新增：小料选择区 -->
      <div class="topping-container" v-if="toppings.length > 0">
        <div class="topping-title">小料:</div>
        <div class="topping-options">
          <button v-for="topping in toppings" :key="topping.id" class="topping-option"
            :class="{ active: selectedToppings.some(item => item.id === topping.id) }" @click="toggleTopping(topping)">
            {{ topping.name }} (+¥{{ topping.price.toFixed(2) }})
          </button>
        </div>
      </div>

      <!-- 价格显示区域修改（将原价格替换为计算后的总价） -->
      <div class="price-box">
        <!-- <span class="current-price">¥{{ totalPrice.toFixed(2) }}</span> -->
        <span class="original-price" v-if="product.original_price">原价:¥{{ product.original_price.toFixed(2) }}</span>
      </div>

      <!-- 商品详情描述 -->
      <div class="detail-desc">
        <h3 class="desc-title">商品详情</h3>
        <div class="desc-content" v-if="product.description">
          {{ product.description }}
          <img :src="product.image_url" class="product-img" v-if="product.image_url" />
        </div>
      </div>

      <Comment></Comment>

      <div class="product-detail">
        <!-- 底部操作栏 -->
        <div class="bottom-bar">
          <button class="btn cart-btn custom-cart-btn" @click="addToCart">加入购物车</button>
          <button class="btn buy-btn" @click="buyNow">立即购买</button>
        </div>
      </div>
    </div>

    <!-- 分享模态框 -->
    <van-popup v-model:show="showShareModal" position="center" :style="{ width: '85%', padding: '0' }">
      <div class="share-modal">
        <!-- 商品信息区域 -->
        <div class="product-info">
          <img :src="product.image_url" :alt="product.name" class="product-thumb" v-if="product.image_url" />
          <div class="product-name">{{ product.name || '商品名称' }}</div>
          <div class="product-price">¥{{ totalPrice.toFixed(2) }}</div>
        </div>

        <!-- 二维码容器（居中放大） -->
        <div class="qrcode-container">
          <div id="qrcode" class="qrcode"></div>
        </div>

        <!-- 底部提示文字 -->
        <van-cell title="显示分享面板" @click="showShare = true" />
        <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" @select="onSelect" />

        <!-- 关闭按钮（底部居中） -->
        <van-button class="close-btn" round size="small" @click="showShareModal = false">
          关闭
        </van-button>
      </div>
    </van-popup>

  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '@/api/history';
import { showSuccessToast, showFailToast, showToast } from 'vant';
import Comment from './Comment.vue';
import QRCode from 'qrcode';

const route = useRoute();
const router = useRouter();
const productId = route.params.id;

const product = ref({});
const specGroups = ref([]);
const toppings = ref([]);
const selectedToppings = ref([]);

const goBack = () => {
  router.back();
};


const showShare = ref(false);
const options = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: '复制链接', icon: 'link' },
];

const onSelect = (option) => {
  showToast(option.name);
  showShare.value = false;
};

// 计算总价
const totalPrice = computed(() => {
  const basePrice = product.value.price || 0;
  const toppingTotal = selectedToppings.value.reduce((sum, t) => sum + t.price, 0);
  return basePrice + toppingTotal;
});

// 获取商品详情
const getProductDetail = async () => {
  try {
    const res = await api.get(`/products/product_detail/${productId}`);
    product.value = res.data;

    const specsRes = await api.get(`/products/${productId}/specs_and_options`);
    if (specsRes.data.specs && specsRes.data.options) {
      formatSpecData(specsRes.data.specs, specsRes.data.options);
    }

    const toppingsRes = await api.get(`/products/get_toppings/${productId}`);
    toppings.value = toppingsRes.data;

  } catch (error) {
    console.log('获取商品详情失败:', error);
    showFailToast('加载商品信息失败，请重试');
  }
};

// 规格和小料处理函数
const formatSpecData = (specs, options) => {
  const groups = specs.map(spec => ({
    name: spec.name,
    options: options.filter(opt => opt.spec.name === spec.name).map(opt => ({ name: opt.name })),
    selectedOption: ''
  }));
  specGroups.value = groups;
  if (groups.length > 0 && groups[0].options.length > 0) {
    groups[0].selectedOption = groups[0].options[0].name;
  }
};

const selectSpec = (groupIndex, optionName) => {
  specGroups.value[groupIndex].selectedOption = optionName;
};

const toggleTopping = (topping) => {
  const index = selectedToppings.value.findIndex(item => item.id === topping.id);
  if (index > -1) {
    selectedToppings.value.splice(index, 1);
  } else {
    selectedToppings.value.push(topping);
  }
};

const getSelectedSpecs = () => {
  return specGroups.value
    .filter(group => group.selectedOption)
    .map(group => `${group.name}:${group.selectedOption}`)
    .join('; ') || '无规格';
};

const getSelectedToppings = () => {
  return selectedToppings.value.length > 0
    ? selectedToppings.value.map(topping => topping.name).join('; ')
    : '无';
};

// 加入购物车方法
const addToCart = async () => {
  // 1. 校验规格是否选全
  const unselectedSpecs = specGroups.value.filter(group => !group.selectedOption);
  if (unselectedSpecs.length > 0) {
    const unselectedNames = unselectedSpecs.map(group => group.name).join('、');
    showFailToast(`请选择：${unselectedNames}`);
    return;
  }

  // 2. 校验商品信息完整性
  if (!product.value.id || !product.value.name) {
    showFailToast('商品信息加载不完整');
    return;
  }

  // 3. 构造购物车数据
  const cartData = {
    user_id: 1, // 根据实际用户ID修改
    product_id: Number(product.value.id),
    product_name: product.value.name || '',
    specs: specGroups.value.map(g => `${g.name}:${g.selectedOption}`).join('; '),
    toppings: selectedToppings.value.map(t => t.name).join('; '),
    quantity: 1,
    price: totalPrice.value.toFixed(2),
    image_url: product.value.image_url || ''
  };

  try {
    // 4. 调用后端接口
    const response = await api.post('/cart/add', cartData);
    showSuccessToast('加入购物车成功');
  } catch (error) {
    console.error('加入购物车失败:', error.response?.data || error.message);
    showFailToast('加入购物车失败，请重试');
  }
};

const buyNow = () => {
  showToast('立即购买功能待实现');
};

// 新增分享模态框相关状态
const showShareModal = ref(false);

// 生成分享二维码
const generateQrcode = async () => {
  // 1. 验证productId有效性
  if (!productId || /\s/.test(productId)) {
    showToast('商品ID无效，无法生成二维码');
    return;
  }

  // 2. 生成规范的商品详情页URL
  // 这里生成的URL就是商品详情页地址
  const shareUrl = `/products/product_detail/${productId}`;

  try {
    await nextTick();
    const canvas = document.createElement('canvas');
    // 将商品详情页URL编码到二维码中
    await QRCode.toCanvas(canvas, shareUrl, {
      width: 220,
      margin: 1,
      color: { dark: '#333', light: '#fff' }
    });
    const container = document.getElementById('qrcode');
    container.innerHTML = '';
    container.appendChild(canvas);
  } catch (error) {
    console.error('生成二维码失败:', error);
    showToast('生成二维码失败，请重试');
  }
};

// 监听模态框显示状态，当显示时生成二维码
watch(showShareModal, (newVal) => {
  if (newVal) {
    generateQrcode();
  }
});



// 页面加载时获取数据
onMounted(() => {
  getProductDetail();
});
</script>

<style scoped>
/* 商品信息样式 */
.product-info {
  margin-bottom: 20px;
  padding: 0 10px;
}

.product-thumb {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  margin: 0 auto 10px;
  display: block;
}

.product-name {
  font-size: 16px;
  text-align: center;
}

.product-price {
  font-size: 18px;
  color: #e63946;
  font-weight: bold;
  margin-bottom: 15px;
}

/* 调整二维码容器间距 */
.qrcode-container {
  margin-bottom: 20px;
  /* 减少底部间距 */
}

/* 分享模态框样式 */
.share-modal {
  background-color: #fff;
  border-radius: 16px;
  padding: 30px 20px;
  text-align: center;
  position: relative;
}

/* 标语文字 */
.modal-slogan {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  line-height: 1.5;
  letter-spacing: 0.5px;
}

.qrcode {
  width: 220px;
  height: 220px;
  margin: 0 auto;
  background-color: #fff;
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 底部提示文字 */
.modal-hint {
  font-size: 15px;
  color: #666;
  margin-bottom: 30px;
  padding: 0 10px;
}

/* 关闭按钮 */
.close-btn {
  background-color: #ff6b00;
  color: white;
  padding: 10px 30px;
  font-size: 16px;
}

/* 顶部 */
.back-label {
  margin-top: 0px;
  text-align: center;
  padding-top: 0px;
  font-size: 20px;
  color: #333;
}

.share-icon {
  color: #333;
  margin-right: 12px;
  cursor: pointer;
}

/* 基础样式 */
.product-detail {
  max-width: 600px;
  margin: 0 auto;
  font-family: "PingFang SC", "Helvetica Neue", sans-serif;
  background-color: #fff;
  padding-bottom: 50px;
}

.img-container {
  width: 100%;
  background-color: #f5f5f5;
  padding: 20px 0;
  text-align: center;
}

.product-img {
  max-width: 80%;
  max-height: 300px;
  object-fit: contain;
}

.info-container {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.product-name {
  font-size: 18px;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.3;
  font-weight: 500;
}

.price-box {
  margin: 10px 0;
}

.current-price {
  font-size: 22px;
  color: #e63946;
  font-weight: bold;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-left: 10px;
}

.stock-sales {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
  margin: 10px 0 20px 0;
}

.spec-container {
  margin: 15px 0;
}

.spec-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 500;
}

.spec-group {
  margin-bottom: 15px;
}

.spec-name {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-option {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
}

.spec-option.active {
  border-color: #ff6b00;
  color: #ff6b00;
  background-color: #fff8f0;
}

.topping-container {
  margin: 15px 0;
  padding: 15px;
  border-top: 1px solid #eee;
}

.topping-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 500;
}

.topping-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.topping-option {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
}

.topping-option.active {
  border-color: #ff6b00;
  color: #ff6b00;
  background-color: #fff8f0;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 50px;
  background-color: #fff;
  border-top: 1px solid #eee;
  max-width: 600px;
  margin: 0 auto;
}

.btn {
  flex: 1;
  border: none;
  font-size: 14px;
  cursor: pointer;
}

.custom-cart-btn {
  color: #fff;
  border-radius: 8px 8px 8px 8px;
  margin-left: 8px;
  margin-right: 5px;
}

.buy-btn {
  color: #fff;
  flex: 1;
  border-radius: 8px 8px 8px 8px;
  margin-right: 8px;
}
</style>